package config

import (
	"github.com/hwcer/cosgo/random"
	"github.com/hwcer/yyds"
)

const GachaRandomName = "GachaConfigRandomName"

func init() {
	yyds.Config.Register(&gachaHandle{})
}

type GachaRandom struct {
	c     *output
	Rate  map[int32]*random.Random
	Group map[int32]*random.Random
	Helps map[uint64]int32
}

func GetGachaRandom() *GachaRandom {
	return yyds.Config.Process.Get(GachaRandomName).(*GachaRandom)
}

// RateRandom 返回卡组 Group
func (this *GachaRandom) RateRandom(rate int32) int32 {
	gachaRateRandom := this.Rate[rate]
	if gachaRateRandom == nil {
		return -1
	}
	id := gachaRateRandom.Roll()
	return id
	//
	//if id <= 0 {
	//	return -1
	//}
	//c := this.c.GachaRate[id]
	//if c == nil {
	//	return 0
	//}
	////return id
	//return c.GetGroup()
}

// GroupRandom 返回卡组 ID
func (this *GachaRandom) GroupRandom(group int32) int32 {
	if g := this.Group[group]; g == nil {
		return -1
	} else {
		return g.Roll()
	}
}
func (this *GachaRandom) HelpsExist(key, num int32) int32 {
	k := this.BuildHelpsKey(key, num)
	return this.Helps[k]
}
func (this *GachaRandom) BuildHelpsKey(key, num int32) uint64 {
	return uint64(key)<<32 + uint64(num)
}

type gachaHandle struct {
	HandleDefault
}

func (this *gachaHandle) Handle(c *yyds.CS, i any) {
	data := i.(*output)
	g := &GachaRandom{c: data}

	//卡池
	rateItems := map[int32]Weight{}
	for _, d := range data.GachaRate {
		v, ok := rateItems[d.Rate]
		if !ok {
			v = Weight{}
			rateItems[d.Rate] = v
		}
		v[d.Id] = d.Val
	}
	g.Rate = map[int32]*random.Random{}
	for k, item := range rateItems {
		g.Rate[k] = random.New(item)
	}

	//卡组
	groupItems := map[int32]Weight{}
	for _, d := range data.GachaGroup {
		v, ok := groupItems[d.Group]
		if !ok {
			v = Weight{}
			groupItems[d.Group] = v
		}
		v[d.Id] = d.Val
	}
	g.Group = map[int32]*random.Random{}
	for k, item := range groupItems {
		g.Group[k] = random.New(item)
	}
	//第N次必中
	g.Helps = map[uint64]int32{}
	for _, helps := range data.GachaHelps {
		k := g.BuildHelpsKey(helps.Key, helps.Num)
		g.Helps[k] = helps.Val
	}

	c.Process.Set(GachaRandomName, g)

}
